#include "filelist.h"

/**
 * creer une nouvelle list
 */
filelist_p flist_new(void){
	filelist_p list;
	list = malloc(sizeof(filelist_t));
	if (list == NULL)
		return NULL;
	flist_init(list);
	return list;
}

void flist_init(filelist_p list){
	list->first = NULL;
	list->last = NULL;
	list->size = 0;
}


return_t flist_insert(filelist_p list, file_p datafile){
	element *new;
	new = malloc(sizeof(element));
	if (new == NULL)
		return RT_ERR;
	new->data = datafile;

	//ajout de l'elt en debut de liste
	new->previous = NULL;
	if(list->size == 0){
		new->next = NULL;
		list->first = new;
		list->last = new;
	}else{
		list->first->previous = new;
		new->next = list->first;
		list->first = new;
	}
	list->size++;
	return RT_OK;
}

return_t flist_remove(filelist_p list, file_p datafile){
	if (list != NULL){
		element *tmp_elt = list->first;

		//parcours de la liste
		while (tmp_elt != NULL){
			if (tmp_elt->data == datafile){
				if (tmp_elt->next == NULL){ //elt trouve en fin de list
					list->last = tmp_elt->previous;
					list->last->next = NULL;
				} else if (tmp_elt->previous == NULL){ // elt trouve en debut de list
					list->first = tmp_elt->next;
					list->first->previous = NULL;
				} else {
					tmp_elt->previous->next = tmp_elt->next;
					tmp_elt->next->previous = tmp_elt->previous;
				}
				free(tmp_elt);
				list--;
				return RT_OK;
			} else
				tmp_elt = tmp_elt->next;
		}
	}
	return RT_ERR;
}

return_t flist_clear(filelist_p list){
	if (list != NULL){
		element *tmp_elt = list->first;
		while(tmp_elt != NULL){
			element *del_elt = tmp_elt;
			tmp_elt = tmp_elt->next;
			free(del_elt);
		}
		list->first = NULL;
		list->last = NULL;
	}
	return(RT_OK);
}

void flist_delete(filelist_p list){
	if (list != NULL){
		element *tmp_elt = list->first;
		while(tmp_elt != NULL){
			element *del_elt = tmp_elt;
			tmp_elt = tmp_elt->next;
			free(del_elt);
		}
		free(list);
		list = NULL;
	}
}

void flist_print(filelist_p list){
	if (list != NULL){
		if (list->size != 0){
			element *tmp_elt = list->first;
			while (tmp_elt != list->last){
				/*fprintf(stdout, "(fichier) nom : %s, cle = %s, taille = %d (ip:port) %s:%d\n",
						tmp_elt->data->name, tmp_elt->data->key, tmp_elt->data->size,
						inet_ntoa(addr->sin_addr), htons(addr->sin_port));*/

				fprintf(stdout, "(fichier) nom : %s, cle = %s, taille = %d\n",
										tmp_elt->data->name, tmp_elt->data->key, tmp_elt->data->size);
				tmp_elt = tmp_elt->next;
			}
		}
		fprintf(stdout, "liste vide\n");
	}
}
file_t * findElementByKey(filelist_t * list,u_char * key){
	if (list->size!=0){
		element *elt;
		elt=malloc(sizeof(element));
		elt=list->last;
		while(elt!=NULL){
			if(strcmp((char *)(elt->data)->key,(char *) key)==0){
				return (elt->data);
			}
			elt=elt->previous;
		}
		
	}
	return NULL;
}